package com.fate.system.utils;

import com.fate.system.enums.PictureSizeEnum;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class ImageCropper {

  // 根据aspectFill策略裁剪图像并缩放
  public static BufferedImage cropAndResizeImage(
      BufferedImage originalImage, PictureSizeEnum photoSize) {
    int targetWidth = photoSize.getWidthPx();
    int targetHeight = photoSize.getHeightPx();

    int originalWidth = originalImage.getWidth();
    int originalHeight = originalImage.getHeight();

    // 计算目标区域和图像的宽高比
    double targetAspectRatio = (double) targetWidth / targetHeight;
    double originalAspectRatio = (double) originalWidth / originalHeight;

    // 计算裁剪区域
    int cropWidth, cropHeight, cropX, cropY;

    if (originalAspectRatio > targetAspectRatio) {
      // 图像较宽
      cropHeight = originalHeight;
      cropWidth = (int) (originalHeight * targetAspectRatio);
      cropX = (originalWidth - cropWidth) / 2;
      cropY = 0;
    } else {
      // 图像较高
      cropWidth = originalWidth;
      cropHeight = (int) (originalWidth / targetAspectRatio);
      cropX = 0;
      cropY = (originalHeight - cropHeight) / 2;
    }

    // 裁剪图像
    BufferedImage croppedImage = originalImage.getSubimage(cropX, cropY, cropWidth, cropHeight);

    // 调整图像大小
    Image tmp = croppedImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
    BufferedImage resizedImage =
        new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = resizedImage.createGraphics();
    g2d.drawImage(tmp, 0, 0, targetWidth, targetHeight, null);
    g2d.dispose();

    return resizedImage;
  }
}
